<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use hf\Recharge;
use aes\AesJs;

use app\admin\model\game\Prize  as PrizeModel;
use app\admin\model\game\Record as RecordModel;
use app\admin\model\game\User   as UserModel;
use app\admin\model\game\Msgcode as CodeModel;
use app\admin\model\game\Ip as IpModel;

date_default_timezone_set('PRC');
header('Access-Control-Allow-Origin: *');
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['initDay','authorize', 'login', 'login2'];
    protected $noNeedRight = ['*'];

    protected $limitIp = 5; //验证码连续错误次数上限
    protected $code_expiretime = 180;//code过期时间

    private  $appid  = 'wx685b6dd0fdef3f36'; 
    private  $secret = 'a87f032d8fd57fa6a2de39f34c900081'; 

    protected $appkey = "62002222e5d2ef03d2323cfec0476b7d";
    protected $openId = "JH479f4c2b02caaa1551613a14c323bcb2"; //聚力互动
    protected $tpl_id = 238672; //聚力互动

    # 测试登录
    # 核销

    public function login()
    {
        $code = $this->request->param("code");
        $userinfo = $this->_getWxUserInfo($code);
        if(!isset($userinfo,$userinfo['openid'])){
            $this->error(__('获取微信信息失败'));
        }
        $mobile = $userinfo["openid"];
        $openid = $userinfo["openid"];
        $userModel = new userModel();
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
            // 创建账户
            $data  = [
                "openid" => $userinfo["openid"],
                "userName" => $userinfo["nickname"],
                "avatar" => $userinfo["headimgurl"]
            ];
            $userModel->createUser($data);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $fields = "userName,avatar,name,tel,compon,job,isJoin,status,page";
            $user = $userModel->getUserinfoByOpenid($openid,$fields);
            $userinfo = $this->auth->getUserinfo();
            $user["token"] = $userinfo["token"];
            $data = ['user'=>$user];
            $this->success(__('Logged in successful'), $data);

        } else {
            $this->error($this->auth->getError());
        }
    }
    public function login2()
    {

        $openid = "a123456";
        if(empty($openid)){$this->error(__('login is fail'));}
        $userModel = new userModel();
        $user = \app\common\model\User::getByMobile($openid);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            // 创建本地用户
            $userName = $this->request->param("userName"); 
            $userHeader = $this->request->param("userHeader"); 
            $user_data = [
                "userName" => $userName,
                "avatar"   => $userHeader,
                "openid"   => $openid
            ];
            //首次进入创建用户
            $userModel->createUser($user_data);
            $ret = $this->auth->register($openid, Random::alnum(), '', $openid, []);
        }
        if ($ret) {
            Sms::flush($openid, 'mobilelogin');
            $fields = "userName,avatar,name,tel,compon,job,isJoin,status,page";
            $user = $userModel->getUserinfoByOpenid($openid,$fields);
            $userinfo = $this->auth->getUserinfo();
            $user["token"] = $userinfo["token"];
            $data = ['user'=>$user];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
        $this->success('请求成功');
    }


    public function sendMsg()
    {
        $tel = $this->request->param("tel");
        if(!(preg_match("/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/",$tel)))
        {
           $this->success('返回成功', ["status"=>400,"message"=>"手机号格式不正确"]);
           return;
        }
        // 发送验证码;
        $CodeModel = new CodeModel();
        $code_res = $CodeModel->getCode($tel);
        $now_time = strtotime('now');
        $return_data = ['status' => 400, 'msg' => "发送失败"];
        if($code_res && $now_time-$this->code_expiretime <  $code_res["senTime"]){
            $return_data = [
                "status" => 400,
                "msg"    => "短信发送太频繁"
            ];
        }else{
            $code = $this->_getCode();
            $RechargeApi = new Recharge($this->appkey,$this->openId);
            $result = $RechargeApi->sendSms($tel,$code,$this->tpl_id);
            // 发送验证码；
            if ($result && $result["error_code"] == 0) {
                $send_res = $CodeModel->sendCode($tel,$code);
                $return_data = ['status' => 200, 'msg' => '验证码发送成功'];
            } 
        }

        $this->success('返回成功', $return_data);
    }

    // 用户提交信息
    public function submite()
    {
        #验证ip
        $checkIp = $this->checkIp(2);
        if(!$checkIp){
            $this->success('请求成功',["status"=>400,"msg"=>"请求过于频繁"]);
        }

        $openid   = $this->auth->mobile;
        $name     = $this->request->param("name");
        $tel = $this->request->param("tel");
        $compon = $this->request->param("compon");
        $job = $this->request->param("job");
        $isJoin = $this->request->param("isJoin");
        $code = $this->request->param("code");
        
        #验证验证码
        $checkCode = $this->checkCode($tel,$code);
        if(!$checkCode){
            $this->success('请求成功',["status"=>400,"msg"=>"验证码错误"]);
        }

        $data = [
            "name" => $name,
            "tel" => $tel,
            "compon" => $compon,
            "job" => $job,
            "isJoin" => $isJoin,
            "status" => 1
        ];

        $userModel = new UserModel();
        $res = $userModel->updateUserInfoByOpenid($openid,$data);
        if($res){
            $this->success('请求成功');
        }else{
            $this->error('请求失败');
        }
    }

    // 更新用户当前页面
    public function updateUserPage()
    {
        $openid = $this->auth->mobile;
        $page = $this->request->param("page");

        $userModel = new UserModel();
        $res = $userModel->updateUserInfoByOpenid($openid,["page"=>$page]);
        if($res){
            $this->success('请求成功'); 
        }else{
            $this->error('请求失败');
        }
    }


    // 检测验证码是否正确
    private  function checkCode($tel,$code){

        $CodeModel = new CodeModel();
        $code_res = $CodeModel->getCode($tel);
        $now_time = strtotime('now');
        if(empty($code_res)){
            return false;
        }

        if($code_res["code"] == $code && $now_time+$this->code_expiretime >  $code_res["senTime"]){
            // 更新验证码状态
            $CodeModel->updateStatusByID($code_res["id"]);
            // ip 检测数据清空
            $ip = $this->request->ip();
            $IpModel = new IpModel();
            $IpModel->updateInfoByIp($ip,0); 
            return true;
        }else{ //验证码错误
            $ip = $this->request->ip();
            $IpModel = new IpModel();
            $ip_res = $IpModel->getInfoByIp($ip);
            if($ip_res){
                $IpModel->ipSetIn($ip); 
            }else{
                $IpModel->addData($ip); 
            }
            return false;
        }
    }

    // 检测ip是否异常
    private function checkIp($status = 1){
        $IpModel = new IpModel();
        $ip = $this->request->ip();
        // 先查库里有没有
        $ipInfo = $IpModel->getInfoByIp($ip);  // 查询  
        if(empty($ipInfo)){  // 没有 -》 插入
            $res = $IpModel->addData($ip);
            return true;
        }else{
            if($this->limitIp <= $ipInfo["num"]){ //超过限制
                // 判断是否可以解封
                $time  = time();
                if($time - 3600 > $ipInfo["updateTime"]){
                    // 可以解封
                    $IpModel->updateInfoByIp($ip,1);
                    return true;
                }else{
                    // 未到解封时间
                    return false;
                }
            }else{
                if($status == 2){
                    $res = $IpModel->updateInfoByIp($ip,$ipInfo["num"]+1);
                }
                return true;
              
            }
            
        }

    }

    // 抽奖
    public function getPrize()
    {
        $openid = $this->auth->mobile;
        //判断是否有机会
        $userModel = new UserModel();
        $fields = "tel,status";
        $user = $userModel->getUserinfoByOpenid($openid,$fields);
        
        if(empty($user["tel"]))
        {
            $this->success('请求成功',["status"=>400,"msg"=>"请先提交信息,再抽奖"]);
        }

        $recordModel = new RecordModel();
        $prize_res = $recordModel->getPrizes($openid);

        if($prize_res)
        {
            $this->success('请求成功',["status"=>400,"msg"=>"您已经抽过奖了"]);
        }

        $prize = $this->_getPrize($user["status"]);
        if($prize)
        {
            // 更新中奖记录
            $RecordModel = new RecordModel();
            $addData = [
                "prize_id" => $prize["prizeId"],
                "openid" => $openid,
            ];
            $add_res = $RecordModel->addData($addData);
            if($add_res)
            {
                $return_data = ["status" => 200,"msg" => "获取成功",
                "prize"=>[
                    "prize_id" => $add_res,
                    "prizeId" => $prize["prizeId"],
                    "name" => $prize["name"],
                    "frameIndex" => $prize["frameIndex"],
                    "type" => $prize["type"],
                    "url" => $prize["url"]
                ]];
            }
            
        }else{
            $return_data = ["status" => 201,"msg" => "奖品已经发送完毕"];
        }
        $this->success('请求成功',$return_data);
    }


    private function _getPrize($status)
    {
        $ConfigModel = new PrizeModel();
        $cards = $ConfigModel->getAll();
        $_cards = [];
        $endNum   = 0;
        $card_index = 0;
        foreach ($cards as $k => $v) {
            //总库存 和 单日限量控制
            if($v['totalNum'] > $v['num'] && $v['dayTotalNum'] > $v['dayNum'])
            {
            	if($status == 1)
            	{
            		// 实物
            		if($v["type"] == 1)
            		{
            			$cards[$k]['startNum'] = $endNum; 
		                $endNum = $endNum + $v['ratio']; //该奖品权重
		                $cards[$k]['endNum'] = $endNum; 
		                array_push($_cards,$cards[$k]);  
            		}

            	}else{
            		// 虚拟 实物 都可以
        			$cards[$k]['startNum'] = $endNum; 
	                $endNum = $endNum + $v['ratio']; //该奖品权重
	                $cards[$k]['endNum'] = $endNum; 
	                array_push($_cards,$cards[$k]);  
            	}
            }

        };

        if(count($_cards) == 0)
        {
            return false;
        }

        $randNum = rand(0,$endNum);

        $card = [];

        //根据权重 取出奖品
        foreach ($_cards as $k => $v) {
            if($v['startNum'] <= $randNum && $v['endNum'] >= $randNum)
            {
                $card = $_cards[$k];

            }
        }

        if(!empty($card)){ //更新数据库  card表  用户表
            // 更新数据库
            $cardUpdateRes = $ConfigModel->updateNumById($card["id"]);
            if($cardUpdateRes){
               return $card;
            }
        }
            
        return false;
    }

    // 获取中奖记录
    public function getPrizes()
    {
        $openid = $this->auth->mobile;
        $RecordModel = new RecordModel();
        $prize = $RecordModel->getPrizes($openid);
        if(empty($prize))
        {
            $this->success('请求成功',["status"=>400,"msg"=>"暂无中奖记录"]);
        }

        $return_data = [
            "openid" => $prize["openid"],
            "name" => $prize["name"],
            "tel" => $prize["tel"],
            "address" => $prize["address"],
            "prize_id" => $prize["id"],
            "status" => $prize["status"],
            "prize_prizeId" => $prize["prize"]["prizeId"],
            "prize_name" => $prize["prize"]["name"],
            "prize_frameIndex" => $prize["prize"]["frameIndex"],
        ];


        $return_data = ["status" => 200,"msg" => "获取成功","prizes"=>$return_data];
        $this->success('请求成功',$return_data);
    }




    public function initDay()
    {
    	// 更新每日库存问题
    	$PrizeModel = new PrizeModel();
    	$res = $PrizeModel->initDay();
    	$UserModel = new UserModel();
    	$user_res = $UserModel->initDay();
    	$msg = "更新成功";
    	if($res){
    		$msg = "-奖品".$msg;
    	}
    	if($user_res)
    	{
    		$msg = "用户数据".$msg;
    	}
    	$this->success('请求成功',["msg"=>$msg]);
    }

    private function getToken($url)
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22");
        curl_setopt($ch, CURLOPT_ENCODING,'gzip');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    private function _getWxUserInfo($code)
    {
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->secret."&code=".$code."&grant_type=authorization_code";
        $user_data = json_decode($this->getToken($url),true);
        if(isset($user_data['access_token'],$user_data['openid']))
        {
            $token    = $user_data['access_token'];
            $openid   = $user_data['openid'];
            $userinfo = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid.'&lang=zh_CN';
            return json_decode($this->getToken($userinfo),true);
        }
        return false;
    }

    public function authorize()
    {
        $redirecturl = urldecode($this->request->param("redirecturl"));
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.urlencode($redirecturl).'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
        header("Location:".$url); 
    }

    private  function _getCode(){
        $chars = "0123456789"; 
        $code = ""; 
        for ( $i = 0; $i < 4; $i++ ) 
        { 
            $code .= $chars[ mt_rand(0, strlen($chars) - 1) ]; 
        }
        return $code;
    }

}
